#include <hilog/log.h>
#include <napi/native_api.h>

#define LOG_TAG "OSG_NAPI"

// 声明外部C函数（在osg_wrapper.cpp中实现）
extern "C" {
    const char* OSG_GetVersion();
    const char* OSG_CheckDisplay();
    const char* OSG_CheckWindowSystem();
    const char* OSG_CheckOpenGL();
    bool OSG_Initialize();
}

// 获取版本信息
static napi_value GetVersion(napi_env env, napi_callback_info info) {
    napi_value result;
    const char* version = OSG_GetVersion();

    napi_create_string_utf8(env, version, NAPI_AUTO_LENGTH, &result);
    OH_LOG_INFO(LOG_APP, "NAPI GetVersion called");
    
    return result;
}

// 检查显示设置
static napi_value CheckDisplay(napi_env env, napi_callback_info info) {
    napi_value result;
    const char* display = OSG_CheckDisplay();
    
    napi_create_string_utf8(env, display, NAPI_AUTO_LENGTH, &result);
    OH_LOG_INFO(LOG_APP, "NAPI CheckDisplay called");
    
    return result;
}

// 检查窗口系统
static napi_value CheckWindowSystem(napi_env env, napi_callback_info info) {
    napi_value result;
    const char* window = OSG_CheckWindowSystem();
    
    napi_create_string_utf8(env, window, NAPI_AUTO_LENGTH, &result);
    OH_LOG_INFO(LOG_APP, "NAPI CheckWindowSystem called");
    
    return result;
}

// 检查OpenGL支持
static napi_value CheckOpenGL(napi_env env, napi_callback_info info) {
    napi_value result;
    const char* opengl = OSG_CheckOpenGL();
    
    napi_create_string_utf8(env, opengl, NAPI_AUTO_LENGTH, &result);
    OH_LOG_INFO(LOG_APP, "NAPI CheckOpenGL called");
    
    return result;
}

// 初始化OSG
static napi_value InitializeOSG(napi_env env, napi_callback_info info) {
    napi_value result;
    bool success = OSG_Initialize();
    
    napi_get_boolean(env, success, &result);
    OH_LOG_INFO(LOG_APP, "NAPI InitializeOSG called, result: %d", success);
    
    return result;
}

EXTERN_C_START
static napi_value Init(napi_env env, napi_value exports) {
    napi_property_descriptor desc[] = {
        {"getVersion", nullptr, GetVersion, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"checkDisplay", nullptr, CheckDisplay, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"checkWindowSystem", nullptr, CheckWindowSystem, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"checkOpenGL", nullptr, CheckOpenGL, nullptr, nullptr, nullptr, napi_default, nullptr},
        {"initialize", nullptr, InitializeOSG, nullptr, nullptr, nullptr, napi_default, nullptr}
    };
    
    napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
    OH_LOG_INFO(LOG_APP, "OSG NAPI module registered");
    
    return exports;
}
EXTERN_C_END

static napi_module osgModule = {
    .nm_version = 1,
    .nm_flags = 0,
    .nm_filename = nullptr,
    .nm_register_func = Init,
    .nm_modname = "osgnapi",
    .nm_priv = ((void*)0),
    .reserved = {0},
};

extern "C" __attribute__((constructor)) void RegisterOSGModule(void) {
    napi_module_register(&osgModule);
}